/**
 * Created by tianrui on 2018/1/29 0029.
 */
layui.config({
    base : "js/"
}).use(['form','layer','jquery','laypage'],function(){
    var form = layui.form(),
        layer = parent.layer === undefined ? layui.layer : parent.layer,
        laypage = layui.laypage,
        $ = layui.jquery;

    //加载页面数据
    var departmentData = '';
    $.get("http://localhost/ci/admin/department/dep_index",  {'token':localStorage.token,'user_token':localStorage.user}, function(data){
        //console.log(JSON.parse(data));
        departmentData = JSON.parse(data);
        // console.log(data);
        //执行加载数据的方法
        departmentList();
    })


    //全选
    form.on('checkbox(allChoose)', function(data){
        var child = $(data.elem).parents('table').find('tbody input[type="checkbox"]:not([name="show"])');
        child.each(function(index, item){
            item.checked = data.elem.checked;
        });
        form.render('checkbox');
    });

    //通过判断文章是否全部选中来确定全选按钮是否选中
    form.on("checkbox(choose)",function(data){
        var child = $(data.elem).parents('table').find('tbody input[type="checkbox"]:not([name="show"])');
        var childChecked = $(data.elem).parents('table').find('tbody input[type="checkbox"]:not([name="show"]):checked')
        if(childChecked.length == child.length){
            $(data.elem).parents('table').find('thead input#allChoose').get(0).checked = true;
        }else{
            $(data.elem).parents('table').find('thead input#allChoose').get(0).checked = false;
        }
        form.render('checkbox');
    })

    function departmentList(){
        //渲染数据
        function renderDate(data,curr){
            var dataHtml = '';
            currData = departmentData.concat().splice(curr*nums-nums, nums);
            if(currData.length != 0){
                for(var i=0;i<currData.length;i++){
                    dataHtml += '<tr>'
                        +  '<td><input type="checkbox" name="checked" lay-skin="primary" lay-filter="choose"></td>'
                        +  '<td>'+currData[i].name+'</td>'
                        +  '<td>'+currData[i].text+'</td>'
                        +  '<td>'
                        +    '<a class="layui-btn layui-btn-mini department_edit" data-id="'+currData[i].id+'"><i class="iconfont icon-edit"></i> 编辑</a>'
                        +    '<a class="layui-btn layui-btn-danger layui-btn-mini department_del" data-id="'+currData[i].id+'"><i class="layui-icon">&#xe640;</i> 删除</a>'
                        +  '</td>'
                        +'</tr>';
                }
            }else{
                dataHtml = '<tr><td colspan="8">暂无数据</td></tr>';
            }
            return dataHtml;
        }

        //分页
        var nums = 3; //每页出现的数据量
        laypage({
            cont : "page",
            pages : Math.ceil(departmentData.length/nums),
            jump : function(obj){
                $(".department_content").html(renderDate(departmentData,obj.curr));
                $('.allDepartment thead input[type="checkbox"]').prop("checked",false);
                form.render();
            }
        })
    }

//--------------弹出页面------------------
    //操作
    $("body").on("click",".department_edit",function(){  //编辑
        var _this = $(this);
        $('.ci_data').val(_this.attr('data-id'));
        var index = layui.layer.open({
            title : "修改部门",
            type : 2,
            content : "http://localhost/ci/admin/department/updateDepartment",
            success : function(layero, index){
                layui.layer.tips('点击此处返回文章列表', '.layui-layer-setwin .layui-layer-close', {
                    tips: 3
                });
            }
        })
        //改变窗口大小时，重置弹窗的高度，防止超出可视区域（如F12调出debug的操作）
        $(window).resize(function(){
            layui.layer.full(index);
        })
        layui.layer.full(index);
        /*layer.alert('您点击了会员编辑按钮，由于是纯静态页面，所以暂时不存在编辑内容，后期会添加，敬请谅解。。。',{icon:6, title:'文章编辑'});*/
    })



    $("body").on("click",".department_del",function(){  //删除
        var _this = $(this);
        layer.confirm('确定删除此角色吗？',{icon:3, title:'提示信息'},function(index){
            //_this.parents("tr").remove();
            for(var i=0;i<departmentData.length;i++){
                if(departmentData[i].id == _this.attr("data-id")){
                    //usersData.splice(i,1);
                    //usersList(usersData);
                    $.ajax({
                        url : "http://localhost/ci/admin/department/dep_del",
                        type : "post",
                        data : {'id':departmentData[i].id, 'token':localStorage.token,'user_token':localStorage.user},
                        dataType : "json",
                        success : function(data){
                            console.log(data);
                            setTimeout(function(){
                                top.layer.msg("部门删除成功！");
                                //重新加载页面
                                location.href='http://localhost/ci/admin/department/'
                            },1000);
                        },
                        error : function (data) {
                            console.log(data);
                            //重新加载页面
                            location.href='http://localhost/ci/admin/department/'
                        }
                    })
                }
            }
            layer.close(index);
        });
    })

    //添加部门
    $(".departmentAdd_btn").click(function(){
        var index = layui.layer.open({
            title : "添加部门",
            type : 2,
            content : "http://localhost/ci/admin/department/addDepartment",
            success : function(layero, index){
                layui.layer.tips('点击此处返回文章列表', '.layui-layer-setwin .layui-layer-close', {
                    tips: 3
                });
            }
        })
        //改变窗口大小时，重置弹窗的高度，防止超出可视区域（如F12调出debug的操作）
        $(window).resize(function(){
            layui.layer.full(index);
        })
        layui.layer.full(index);
    })



    //------------------------查询操作---------------
    //查询
    $(".search_btn").click(function(){
        var userArray = [];
        if($(".search_input").val() != ''){
            var index = layer.msg('查询中，请稍候',{icon: 16,time:false,shade:0.8});
            setTimeout(function(){
                $.ajax({
                    url : "http://localhost/ci/admin/department/dep_index",
                    type : "get",
                    data:{'token':localStorage.token,'user_token':localStorage.user},
                    dataType : "json",
                    success : function(data){
                        if(window.sessionStorage.getItem("addDepartment")){
                            var addDepartment = window.sessionStorage.getItem("addDepartment");
                            addDepartment = JSON.parse(addDepartment).concat(data);
                        }else{
                            usersData = data;
                        }
                        for(var i=0;i<departmentData.length;i++){
                            var departmentStr = departmentData[i];
                            var selectStr = $(".search_input").val();
                            function changeStr(data){
                                var dataStr = '';
                                var showNum = data.split(eval("/"+selectStr+"/ig")).length - 1;
                                if(showNum > 1){
                                    for (var j=0;j<showNum;j++) {
                                        dataStr += data.split(eval("/"+selectStr+"/ig"))[j] + "<i style='color:#03c339;font-weight:bold;'>" + selectStr + "</i>";
                                    }
                                    dataStr += data.split(eval("/"+selectStr+"/ig"))[showNum];
                                    return dataStr;
                                }else{
                                    dataStr = data.split(eval("/"+selectStr+"/ig"))[0] + "<i style='color:#03c339;font-weight:bold;'>" + selectStr + "</i>" + data.split(eval("/"+selectStr+"/ig"))[1];
                                    return dataStr;
                                }
                            }
                            //姓名
                            if(departmentStr.name.indexOf(selectStr) > -1){
                                departmentStr["name"] = changeStr(departmentStr.name);
                            }
                            //部门
                            if(departmentStr.remark.indexOf(selectStr) > -1){
                                departmentStr["text"] = changeStr(departmentStr.text);
                            }

                        }
                        departmentData = departmentArray;
                        rolesList(departmentData);
                    }
                })
                layer.close(index);
            },2000);
        }else{
            layer.msg("请输入需要查询的内容");
        }
    })

})
